<script setup lang="ts">
import { ref, reactive, onMounted, h } from "vue";
import { DynamicTable } from "@/components/DynamicTable";
import { TableColumn, PaginationConfig } from "@/components/DynamicTable/types";
import DynamicForm from "@/components/DynamicForm/index.vue";
import { FormItemConfig } from "@/components/DynamicForm/types";
import {
  ElMessage,
  ElTag,
  ElButton,
  ElDialog,
  ElDescriptions,
  ElDescriptionsItem,
  ElCard,
  ElInput,
} from "element-plus";
import { Refresh, View, Document } from "@element-plus/icons-vue";
import {
  getAssetStatistics,
  queryMatchedAssets,
  getProcessingLogs,
} from "../servers";

const props = defineProps<{
  task: string;
}>();

const loading = ref(false);
const loadingAnalysis = ref(false);
const correlationData = ref<any>(null);
const correlationDetails = ref<any[]>([]);

const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

const queryForm = reactive({
  intelligence_id: "",
  ip_range: "",
  service_type: "",
  risk_level: "",
});

const queryConfig: FormItemConfig[] = [
  {
    key: "intelligence_id",
    name: "情报ID",
    type: "input",
    labelWidth: "120px",
    placeholder: "请输入情报ID（可选）",
  },
  {
    key: "ip_range",
    name: "IP范围",
    type: "input",
    labelWidth: "120px",
    placeholder: "例如：172.16.1.0/24",
  },
  {
    key: "service_type",
    name: "服务类型",
    type: "input",
    labelWidth: "120px",
    placeholder: "例如：http",
  },
  {
    key: "risk_level",
    name: "风险等级",
    type: "select",
    labelWidth: "120px",
    params: {
      clearable: true,
      showPlaceholder: false,
      options: [
        { label: "全部", value: "" },
        { label: "高风险", value: "high" },
        { label: "中风险", value: "medium" },
        { label: "低风险", value: "low" },
      ],
    },
  },
];

const getRiskLevelTag = (level: string) => {
  const levelMap: Record<string, any> = {
    高风险: { text: "高风险", type: "danger" },
    中风险: { text: "中风险", type: "warning" },
    低风险: { text: "低风险", type: "info" },
  };
  return levelMap[level] || { text: level, type: "info" };
};

const columns = ref<TableColumn[]>([
  {
    label: "资产信息",
    prop: "asset_info",
    minWidth: 250,
    show: true,
    render: (row) => {
      const info = row.compliance_info || {};
      const assetName = info.asset_name || info.asset_ip || row.ip || "-";
      const ip = info.asset_ip || row.ip || "-";
      let portInfo = "-";
      if (info.start_port !== undefined && info.start_port !== null) {
        if (info.start_port === info.end_port) {
          portInfo = String(info.start_port);
        } else if (info.end_port !== undefined && info.end_port !== null) {
          portInfo = `${info.start_port}-${info.end_port}`;
        } else {
          portInfo = String(info.start_port);
        }
      }
      const serviceType = info.service_type || "-";
      return h("div", {}, [
        h("div", { style: "font-weight: bold; margin-bottom: 4px" }, assetName),
        h(
          "div",
          { style: "color: #666; font-size: 12px" },
          `IP: ${ip} | 端口: ${portInfo} | 服务: ${serviceType}`
        ),
      ]);
    },
  },
  {
    label: "部门/责任人",
    prop: "responsible",
    minWidth: 200,
    show: true,
    slot: "responsible",
  },
  {
    label: "操作系统",
    prop: "os",
    width: 150,
    show: true,
    render: (row) => {
      const info = row.compliance_info || {};
      const os = info.operating_system || "-";
      const osVersion = info.os_version ? ` (${info.os_version})` : "";
      return h("span", {}, os + osVersion);
    },
  },
  {
    label: "设备信息",
    prop: "device_info",
    width: 150,
    show: true,
    render: (row) => {
      const info = row.compliance_info || {};
      const deviceType = info.asset_device_type || "-";
      const manufacturer = info.manufacturer_info || "";
      return h("div", {}, [
        h("div", {}, deviceType),
        manufacturer
          ? h("div", { style: "color: #666; font-size: 12px" }, manufacturer)
          : null,
      ]);
    },
  },
  {
    label: "操作",
    prop: "action",
    width: 100,
    fixed: "right",
    show: true,
    slot: "action",
  },
]);

const showDetailDialog = ref(false);
const showLogsDialog = ref(false);
const assetDetail = ref<any>(null);
const loadingDetail = ref(false);

// 处理日志相关
const loadingLogs = ref(false);
const logList = ref<any[]>([]);
const logPagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 50,
  total: 0,
  pageSizes: [50, 100, 200],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

const logSearchForm = reactive({
  log_level: "",
  operation_type: "",
  keyword: "",
});

const logColumns = ref<TableColumn[]>([
  {
    label: "时间",
    prop: "timestamp",
    width: 180,
    show: true,
  },
  {
    label: "级别",
    prop: "log_level",
    width: 100,
    show: true,
    render: (row) => {
      const levelMap: Record<string, any> = {
        INFO: { text: "信息", type: "success" },
        WARN: { text: "警告", type: "warning" },
        ERROR: { text: "错误", type: "danger" },
        DEBUG: { text: "调试", type: "info" },
      };
      const levelInfo = levelMap[row.log_level] || {
        text: row.log_level,
        type: "info",
      };
      return h(ElTag, { type: levelInfo.type, size: "small" }, levelInfo.text);
    },
  },
  {
    label: "操作类型",
    prop: "operation_type",
    width: 150,
    show: true,
  },
  {
    label: "消息",
    prop: "message",
    minWidth: 300,
    show: true,
  },
  {
    label: "耗时",
    prop: "execution_time",
    width: 100,
    show: true,
  },
]);

const fetchStatistics = async () => {
  loadingAnalysis.value = true;
  try {
    const { data } = await getAssetStatistics({
      include_details: true,
    });
    if (data) {
      correlationData.value = {
        analysis_summary: data.statistics || {},
      };
    }
  } catch (error) {
    ElMessage.error("获取资产统计信息失败");
  } finally {
    loadingAnalysis.value = false;
  }
};

const fetchMatchedAssets = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      per_page: pagination.pageSize,
    };

    if (queryForm.intelligence_id) {
      params.intelligence_id = parseInt(String(queryForm.intelligence_id));
    }
    if (queryForm.ip_range) {
      params.ip_range = queryForm.ip_range;
    }
    if (queryForm.service_type) {
      params.service_type = queryForm.service_type;
    }
    if (queryForm.risk_level) {
      params.risk_level = queryForm.risk_level;
    }

    const { data } = await queryMatchedAssets(params);
    if (data) {
      // 适配返回数据结构：results 数组
      correlationDetails.value =
        data.results || data.items || data.assets || [];
      pagination.total = data.total || data.pagination?.total_items || 0;
    }
  } catch (error) {
    ElMessage.error("查询匹配资产失败");
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  pagination.currentPage = 1;
  fetchMatchedAssets();
};

const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchMatchedAssets();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchMatchedAssets();
};

const handleViewDetail = (row: any) => {
  assetDetail.value = row;
  showDetailDialog.value = true;
};

const handleViewLogs = async () => {
  showLogsDialog.value = true;
  await fetchLogs();
};

const fetchLogs = async () => {
  loadingLogs.value = true;
  try {
    const params: any = {
      pagination: {
        page: logPagination.currentPage,
        page_size: logPagination.pageSize,
      },
    };

    if (logSearchForm.log_level) {
      params.query_config = {
        ...params.query_config,
        log_level: logSearchForm.log_level,
      };
    }
    if (logSearchForm.operation_type) {
      params.query_config = {
        ...params.query_config,
        operation_type: logSearchForm.operation_type,
      };
    }
    if (logSearchForm.keyword) {
      params.query_config = {
        ...params.query_config,
        keyword: logSearchForm.keyword,
      };
    }

    const { data } = await getProcessingLogs(params);
    if (data) {
      logList.value = data.log_records || [];
      logPagination.total = data.pagination_info?.total_records || 0;
    }
  } catch (error) {
    ElMessage.error("获取处理日志失败");
  } finally {
    loadingLogs.value = false;
  }
};

const handleLogPageChange = (page: number) => {
  logPagination.currentPage = page;
  fetchLogs();
};

const handleLogSizeChange = (size: number) => {
  logPagination.pageSize = size;
  logPagination.currentPage = 1;
  fetchLogs();
};

const handleLogSearch = () => {
  logPagination.currentPage = 1;
  fetchLogs();
};

const handleLogReset = () => {
  Object.assign(logSearchForm, {
    log_level: "",
    operation_type: "",
    keyword: "",
  });
  logPagination.currentPage = 1;
  fetchLogs();
};

// 解析部门层级
const parseDepartment = (department: any) => {
  if (!department || typeof department !== "string") {
    return [];
  }
  return department.split("/").filter(Boolean);
};

onMounted(() => {
  fetchStatistics();
  fetchMatchedAssets();
});
</script>

<template>
  <div>
    <!-- 查询控制面板 -->
    <el-card shadow="never" style="margin-bottom: 10px">
      <template #header>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <span>资产查询</span>
        </div>
      </template>
      <div
        style="display: flex; gap: 10px; align-items: center; flex-wrap: wrap"
      >
        <div style="display: flex; gap: 10px; align-items: center">
          <div style="display: flex; gap: 16px; flex-wrap: wrap">
            <div
              v-for="config in queryConfig"
              :key="config.key"
              style="display: flex; align-items: center; gap: 8px"
            >
              <label style="width: 120px; text-align: right"
                >{{ config.name }}：</label
              >
              <el-select
                v-if="config.type === 'select'"
                v-model="queryForm[config.key]"
                :placeholder="config.placeholder"
                clearable
                style="width: 200px"
              >
                <el-option
                  v-for="opt in config.params?.options"
                  :key="opt.value"
                  :label="opt.label"
                  :value="opt.value"
                />
              </el-select>
              <el-input
                v-else-if="config.type === 'input'"
                v-model="queryForm[config.key]"
                :placeholder="config.placeholder"
                style="width: 200px"
                :type="config.key === 'intelligence_id' ? 'number' : 'text'"
              />
            </div>
          </div>
        </div>
        <div style="margin-left: auto">
          <el-button type="primary" :loading="loading" @click="handleQuery">
            查询
          </el-button>
          <el-button
            :icon="Refresh"
            :loading="loadingAnalysis"
            @click="fetchStatistics"
          >
            刷新统计
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 关联概览 -->
    <el-card
      v-if="correlationData?.analysis_summary"
      style="margin-bottom: 10px"
    >
      <template #header>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <span>关联概览</span>
        </div>
      </template>
      <el-descriptions :column="4" border>
        <el-descriptions-item label="总资产">
          <el-tag type="info" size="large">{{
            correlationData.analysis_summary.total_assets || 0
          }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="关联资产">
          <el-tag type="success" size="large">{{
            correlationData.analysis_summary.correlated_assets || 0
          }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="关联率">
          <el-tag type="success" size="large">
            {{
              correlationData.analysis_summary.correlation_rate
                ? (
                    correlationData.analysis_summary.correlation_rate * 100
                  ).toFixed(1)
                : 0
            }}%
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="总情报数">
          <el-tag type="info" size="large">{{
            correlationData.analysis_summary.total_intelligence || 0
          }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="高风险">
          <el-tag type="danger" size="large">{{
            correlationData.analysis_summary.high_risk_assets || 0
          }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="中风险">
          <el-tag type="warning" size="large">{{
            correlationData.analysis_summary.medium_risk_assets || 0
          }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="低风险">
          <el-tag type="info" size="large">{{
            correlationData.analysis_summary.low_risk_assets || 0
          }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="平均置信度">
          <el-tag type="success" size="large">
            {{
              correlationData.analysis_summary.average_confidence
                ? correlationData.analysis_summary.average_confidence.toFixed(2)
                : 0
            }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 关联详情 -->
    <el-card>
      <template #header>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <span>关联详情</span>
          <el-button
            type="primary"
            :icon="Document"
            size="small"
            @click="handleViewLogs"
          >
            查看处理日志
          </el-button>
        </div>
      </template>

      <DynamicTable
        :columns="columns"
        :data="correlationDetails"
        :loading="loading"
        :pagination="pagination"
        @current-page-change="handlePageChange"
        @size-change="handleSizeChange"
      >
        <template #action="{ row }">
          <el-button
            type="primary"
            size="small"
            :icon="View"
            @click="handleViewDetail(row)"
          >
            详情
          </el-button>
        </template>

        <!-- 部门/责任人列插槽 -->
        <template #responsible="{ row }">
          <div
            v-if="row.compliance_info?.asset_department"
            class="department-item"
          >
            <div class="dept-path">
              <span
                v-for="(part, partIndex) in parseDepartment(
                  row.compliance_info.asset_department
                )"
                :key="partIndex"
                class="dept-level"
                :class="{
                  'dept-level-last':
                    partIndex ===
                    parseDepartment(row.compliance_info.asset_department)
                      .length -
                      1,
                }"
              >
                {{ part }}
              </span>
            </div>
          </div>
          <span v-else style="color: #909399">-</span>
          <div
            v-if="row.compliance_info?.asset_responsible_person"
            style="color: #666; font-size: 12px; margin-top: 4px"
          >
            {{ row.compliance_info.asset_responsible_person }}
          </div>
        </template>
      </DynamicTable>
    </el-card>

    <!-- 资产详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="资产详情"
      width="1200px"
      v-loading="loadingDetail"
    >
      <div v-if="assetDetail">
        <el-card shadow="never" style="margin-bottom: 20px">
          <el-descriptions title="基本信息" :column="2" border>
            <el-descriptions-item label="IP地址">{{
              assetDetail.compliance_info?.asset_ip || assetDetail.ip || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="资产名称">{{
              assetDetail.compliance_info?.asset_name || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="端口范围">
              {{
                assetDetail.compliance_info?.start_port ===
                assetDetail.compliance_info?.end_port
                  ? assetDetail.compliance_info?.start_port
                  : `${assetDetail.compliance_info?.start_port || ""}-${
                      assetDetail.compliance_info?.end_port || ""
                    }`
              }}
            </el-descriptions-item>
            <el-descriptions-item label="服务类型">{{
              assetDetail.compliance_info?.service_type || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="操作系统">{{
              assetDetail.compliance_info?.operating_system || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="系统版本">{{
              assetDetail.compliance_info?.os_version || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="设备类型">{{
              assetDetail.compliance_info?.asset_device_type || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="厂商信息">{{
              assetDetail.compliance_info?.manufacturer_info || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="设备版本">{{
              assetDetail.compliance_info?.device_version || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="资产类型">{{
              assetDetail.compliance_info?.asset_type || "-"
            }}</el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-card shadow="never" style="margin-bottom: 20px">
          <el-descriptions title="责任信息" :column="2" border>
            <el-descriptions-item label="公司">{{
              assetDetail.compliance_info?.asset_company || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="部门">{{
              assetDetail.compliance_info?.asset_department || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="资产责任人">{{
              assetDetail.compliance_info?.asset_responsible_person || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="责任人联系方式">{{
              assetDetail.compliance_info?.responsible_contact || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="端口责任部门">{{
              assetDetail.compliance_info?.port_responsible_department || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="端口责任人">{{
              assetDetail.compliance_info?.port_responsible_person || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="端口责任人联系方式">{{
              assetDetail.compliance_info?.port_responsible_contact || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="跨部门">{{
              assetDetail.compliance_info?.is_cross_department ? "是" : "否"
            }}</el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-card shadow="never" style="margin-bottom: 20px">
          <el-descriptions title="其他信息" :column="2" border>
            <el-descriptions-item label="序列号">{{
              assetDetail.compliance_info?.serial_number || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="域名">{{
              assetDetail.compliance_info?.asset_domain || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="软件/中间件信息">{{
              assetDetail.compliance_info?.software_middleware_info || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="是否有Web界面">{{
              assetDetail.compliance_info?.has_web_interface ? "是" : "否"
            }}</el-descriptions-item>
            <el-descriptions-item label="Web界面URL" :span="2">{{
              assetDetail.compliance_info?.web_interface_url || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">{{
              assetDetail.compliance_info?.remarks || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="资产记录信息" :span="2">{{
              assetDetail.compliance_info?.asset_record_info || "-"
            }}</el-descriptions-item>
          </el-descriptions>
        </el-card>
      </div>
    </el-dialog>

    <!-- 处理日志对话框 -->
    <el-dialog
      v-model="showLogsDialog"
      title="处理日志查询"
      width="1200px"
      @close="showLogsDialog = false"
    >
      <el-card shadow="never" style="margin-bottom: 10px">
        <DynamicForm
          v-model="logSearchForm"
          :form-config="[
            {
              key: 'log_level',
              name: '日志级别',
              type: 'select',
              labelWidth: '100px',
              params: {
                clearable: true,
                showPlaceholder: false,
                options: [
                  { label: '全部', value: '' },
                  { label: '信息', value: 'INFO' },
                  { label: '警告', value: 'WARN' },
                  { label: '错误', value: 'ERROR' },
                  { label: '调试', value: 'DEBUG' },
                ],
              },
            },
            {
              key: 'operation_type',
              name: '操作类型',
              type: 'select',
              labelWidth: '100px',
              params: {
                clearable: true,
                showPlaceholder: false,
                options: [
                  { label: '全部', value: '' },
                  { label: '情报上传', value: 'upload' },
                  { label: '匹配分析', value: 'match' },
                  { label: 'POC推荐', value: 'poc_recommendation' },
                  { label: '工作流执行', value: 'workflow' },
                ],
              },
            },
            {
              key: 'keyword',
              name: '关键词',
              type: 'input',
              labelWidth: '100px',
              placeholder: '搜索关键词',
            },
          ]"
          :gutter="16"
          label-width="100px"
          type="search"
          @search="handleLogSearch"
          @reset="handleLogReset"
        />
      </el-card>

      <DynamicTable
        :columns="logColumns"
        :data="logList"
        :loading="loadingLogs"
        :pagination="logPagination"
        @current-page-change="handleLogPageChange"
        @size-change="handleLogSizeChange"
      />
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
// 部门层级样式
.department-item {
  padding: 6px 8px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #409eff;
  transition: all 0.2s ease;
}

.department-item:hover {
  background: #e6f7ff;
  border-left-color: #1890ff;
}

.dept-path {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 4px;
}

.dept-level {
  font-size: 12px;
  color: #606266;
  padding: 2px 4px;
  border-radius: 3px;
  background: #fff;
  border: 1px solid #e4e7ed;
  transition: all 0.2s ease;
}

.dept-level-last {
  color: #409eff;
  font-weight: 500;
  background: #e6f7ff;
  border-color: #91d5ff;
}
</style>
